package com.cht.sys.web;

import java.io.IOException;

import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.cht.sys.CommonUtil;
import com.cht.sys.security.MBMSPrincipal;

/**
 * Servlet Filter implementation class AuthenticationFilter
 */
public class AuthenticationFilter implements Filter {

    /**
     * Default constructor.
     */
    public AuthenticationFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletResponse httpResponse = (HttpServletResponse)response;
		HttpServletRequest httpRequest = (HttpServletRequest)request;

		HttpSession session = httpRequest.getSession(true);
		LoginContext lc = (LoginContext)session.getAttribute("javax.security.auth.login");

		try {
			if (lc == null) {
				httpResponse.sendRedirect(httpResponse.encodeRedirectURL("/NIAS_Redirect.jsp"));
			} else {
				Subject subject = lc.getSubject();

				if (subject == null) {
					httpResponse.sendRedirect(httpResponse.encodeRedirectURL("/NIAS_Redirect.jsp"));
				} else {
					MBMSPrincipal principal = new MBMSPrincipal("AWW00");
					if (!subject.getPrincipals().contains(principal)) {
						httpResponse.sendRedirect(httpResponse.encodeRedirectURL("/NIAS_Redirect.jsp"));
					} else {
						chain.doFilter(request, response);
					}
				}
			}
		} catch (Exception e) {
			CommonUtil.setLog4J("error", "com.cht.sys.sso", "AuthenticationFilter.doFilter(): " + e.toString());
			httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN);
			return;
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}
}
